<?php

/**
 * 基础类文件，添加一些公用类函数
 */

namespace BaseBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Filesystem\Filesystem;
use Eventviva\ImageResize;
use Utils\Requests;
use Utils\Responses;

define ('LIKE', 'LIKE');
define ('EQUAL', '=');
define ('GREATER', '>');
define ('LESS_THAN', '<');
define ('GREATER_EQUAL', '>=');
//header ("Access-Control-Allow-Origin:*");

class BaseController extends Controller
{

    /**
     * 判断手机是否可以使用
     *
     * @param $phone
     * @param $type
     * @return array
     */
    public function verifyPhone($phone, $type = 1)
    {
        $conn = $this->get('database_connection');
        $user = $conn->fetchAssoc("SELECT id,status FROM user WHERE phone = ?", array($phone));
        if ($type){
            if (empty($user))
                return array('errorCode'=>0);
            if ($user['status'] == 0)
                return array('errorCode'=>1, 'message'=>'该手机已被后台禁用，请联系平台处理或更换手机号');
            return array('errorCode'=>1, 'message'=>'该手机已被注册');
        }else{
            if (!empty($user)){
                if ($user['status'] == 0)
                    return array('errorCode'=>1, 'message'=>'该手机已被后台禁用，请联系平台处理或更换手机号');
                return array('errorCode'=>0);
            }else
                return array('errorCode'=>1, 'message'=>'该手机未注册');
        }

    }

    /**
     * 判断邀请码是否正确
     *
     * @param $code
     * @return bool
     */
    public function verifyCode($code)
    {
        return $this->get('database_connection')->fetchColumn("SELECT 1 FROM user WHERE invitation_code = ?", array($code)) ? true : false;
    }

    /**
     * 获取上个页面的地址Url
     *
     * @param $routeName
     * @return mixed|string
     */
    public function getForwardUrl($routeName = '')
    {
        if ( $routeName ) {
            $redirect = $this->generateUrl($routeName);
        } else {
            if ($this->get('services.sessions')->get('redirect')) {
                $redirect = $this->get('services.sessions')->get('redirect');
            } elseif ($this->get('request')->server->has('HTTP_REFERER')) {
                $redirect = $this->get('request')->server->get('HTTP_REFERER');
            } else {
                $redirect = $this->get('request')->getSchemeAndHttpHost() . $this->get('request')->getBasePath();
            }
        }

        return $redirect;
    }

    /**
     * 发送短信
     *
     * @param $phone
     * @param $content
     * @param $sendtime
     * @return array
     */
    public function send($phone, $content, $sendtime = '')
    {
        $post_data = array();
        $post_data['userid'] = $this->getParameter('sms_userid');
        $post_data['account'] = $this->getParameter('sms_username');
        $post_data['password'] = $this->getParameter('sms_password');
        $post_data['content'] = $this->getParameter('sms_content_prefix'). $content;
        $post_data['mobile'] = $phone;
        $post_data['sendtime'] = $sendtime; //不定时发送，值为''，定时发送，输入格式YYYYMMDDHHmmss的日期值
        $url = 'http://123.58.251.213:8080/sms.aspx?action=send';
        $o = '';
        foreach ($post_data as $k => $v) {
            $o .= "$k=" . urlencode($v) . '&';
        }
        $post = substr($o, 0, -1); // 去除最后一个&符号
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //如果需要将结果直接返回到变量里，那加上这句。
        $xml = curl_exec($ch);

        $xmlparser = xml_parser_create();
        xml_parse_into_struct($xmlparser, $xml, $values);

        xml_parser_free($xmlparser);

        $result = array();
        foreach ($values as $v) {
            if (array_key_exists('tag', $v) && array_key_exists('value', $v)) {
                $result[$v['tag']] = $v['value'];
            }
        }

        return $result;
    }

    /**
     * 上传图片
     *
     * @param $inputName 这个是表单上file类型的input的name值
     * @param $path 图片上传路径
     * @param $filename 图片名称，不包括扩展名
     * @param bool $type 是否验证文件类型
     * @return array 图片的全名，包括扩展名
     */
    public function uploadImage($inputName, $path, $filename, $type = false)
    {
        if (!file_exists($path)) {
            mkdir($path, 0755);
        }

        $storage = new \Upload\Storage\FileSystem($path);
        $file = new \Upload\File($inputName, $storage);

        if ($file->getName() != '') {//有新的文件
            $file->setName($filename);

            // Validate file upload
            // MimeType List => http://www.webmaster-toolkit.com/mime-types.shtml
            if ($type)
                $file->addValidations(array(
                    new \Upload\Validation\Size($this->getParameter('upload_max_size'))
                ));
            else
                $file->addValidations(array(
                    new \Upload\Validation\Mimetype(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg')),
                    new \Upload\Validation\Size($this->getParameter('upload_max_size'))
                ));

            try {
                $file->upload();
                $result['name'] = $path . '/' . $file->getNameWithExtension();
            } catch (\Exception $e) {

                $result['errors'] = $file->getErrors();
            }
        }

        return $result;
    }

    /**
     * 修改图片尺寸
     *
     * @param $image
     * @param int $width
     * @param int $height
     * @return string
     */
    public function resize($image, $width = 200, $height = 200)
    {
        if (!file_exists($image) || !is_file($image)) {
            return '';
        }

        $info = pathinfo($image);
        $new_image = substr($image, 0, strrpos($image, '.')) . '-' . $width . 'x' . $height . '.' . $info['extension'];

        if (!file_exists($new_image) || (filemtime($image) > filemtime($new_image))) {
            $imageResize = new ImageResize($image);
            $imageResize->resize($width, $height);
            $imageResize->save($new_image, IMAGETYPE_JPEG, 80);
        }

        return $new_image;
    }

    /**
     * 获得Settings表中的数据
     *
     * @param $configKey
     * @return mixed
     */
    protected function getSettingsData($configKey)
    {
        if ( is_array($configKey) ) {
            $configKeys = implode(',', $configKey);

            $configValueArray = $this->get('database_connection')->fetchAssoc("SELECT config_key, config_value FROM settings WHERE config_key IN (" . $configKeys . ")");
            $data = array();
            foreach ($configValueArray as $value) {
                if ( !in_array($value['config_key'], $configValueArray) ) {
                    $data[$value['config_key']] = NULL;
                } else {
                    $data[$value['config_key']] = $value['config_value'];
                }
            }

            return $data ?: '';
        }

        $data = $this->get('database_connection')->fetchColumn("SELECT config_value FROM settings WHERE config_key = ?", array($configKey));

        return $data === false ? '' : $data;
    }

    /**
     * 返回值处理
     *
     * @param int $errorCode
     * @param string $message
     * @param array $data
     * @return array|Response
     */
    protected function jsonResponse($message = '操作失败', $errorCode = 1,  $data = array())
    {
        return Responses::json($message, $errorCode, $data);
    }

    /**
     * 计算字符串长度（非字符长度）
     * @param $str 需要计算的字符
     * @param string $key 编码方式
     * @return mixed
     */
    public function getLength($str, $key='UTF8')
    {
        $length = mb_strlen($str,$key);

        return $length;
    }

    /**
     * 删除全部的空格
     *
     * @param $str
     * @return mixed
     */
    public function trimAll($str)
    {
        $arr=array(" ","　","\t","\n","\r");$hou=array("","","","","");
        return str_replace($arr,$hou,$str);
    }

    /**
     * 得到url
     *
     * @param string $str
     * @param array $arr
     * @return string
     */
    public function getURL($str = '', $arr = array())
    {
        if (empty($arr)) {
            return $this->get('request')->getSchemeAndHttpHost() . $this->generateUrl($str);
        } else {
            return $this->get('request')->getSchemeAndHttpHost() . $this->generateUrl($str, $arr);
        }
    }

    /**
     * 获取当前时间
     */
    public function getTime()
    {
        return date('Y-m-d H:i:s', time());
    }

    /**
     * 获取当前时间
     */
    public function getTimes()
    {
        return date('Y-m-d', time());
    }

    /**
     * 设置长文本内容
     *
     * @param $content
     * @return mixed
     */
    public function setContent($content)
    {
        return preg_replace_callback('/[\xf0-\xf7].{3}/', function ($r) {
            return '@E' . base64_encode($r[0]);
        }, $content);
    }


    /**
     * 得到处理后的长文本内容
     *
     * @param $content
     * @return mixed
     */
    public function getContent($content)
    {
        return preg_replace_callback('/@E(.{6}==)/', function ($r) {
            return base64_decode($r[1]);
        }, $content);
    }

    /**
     * 返回值处理
     *
     * @param $data
     * @param Request $request
     * @return mixed
     */
    public function getData($data, Request $request)
    {
        $judge = $this->judgeLogin($request);
        if (isset($judge['id'])){
            $data['is_vip'] = $this->isVip($judge['id']);
            $data['balance'] = $this->get('database_connection')->fetchColumn("SELECT balance FROM user WHERE id = ?", array($judge['id']));
        }
        $data['time'] = $this->getTime();
        $data['timestamp'] = time();

        return $data;
    }

    /**
     * 判断用户是否是会员
     *
     * @param $user_id
     * @return int
     */
    public function isVip($user_id)
    {
        return $this->get('database_connection')->fetchColumn("SELECT 1 FROM recharge WHERE user_id = ? AND is_pay = 1 AND trade_no IS NOT NULL", array($user_id)) ? 1 : 0;
    }

    /**
     * 销毁数组空值
     *
     * @param $data
     * @return mixed
     */
    public function arrayFilter($data)
    {
        foreach ($data AS $item=>$value){
            if ($value === '' || $value === null) {
                unset($data[$item]);
            }
        }

        return $data;
    }

    /*
     *分页
     * @param $total    总数
     * @param $page     页数
     * @param $limit    行数
     * @param $url      链接
     * @param $route    路由
     * @return string
     */
    public function paging($total, $page, $limit, $url, $route)
    {
        $pagination = new Pagination();
        $pagination->total = $total;
        $pagination->page = $page;
        $pagination->limit = $limit;
        $pagination->url = $this->generateUrl($route) . '?page={page}' . $url;

        $render = $pagination->render();
//        $url = $this->generateUrl($route) . '?page=' . $page . $url;

//        return array('render' => $render, 'url' => $url);
        $html = '<div class="row"  style="width: 70%; margin-left: 15%;"><tfoot ><tr><td colspan="13" class="footable-visible"><ul id="page" class="pagination pull-right">' . $render . '</ul> </td></tr> </tfoot></div>';

        return $html;
    }

    /**
    /* 推送基础方法
     *
     * @param $alias
     * @param $content
     * @param array $remarks_array
     * @return string
     */
    public function baseJPush1($alias, $content, $remarks_array = array())
    {
        $client = new \JPush\Client($this->getParameter('user_app_key'), $this->getParameter('user_master_secret'), $this->getParameter('jpush_logs_path'));

        $push_setting_array = array(
            'sound' => 'default',   //设置提示声
            'extras' => $remarks_array  //设置自定义参数
        );

        $push = $client->push();

        $push->setPlatform('all');
        if ($alias == 'all') {
            $push->addAllAudience();
        } else {
            $push->addAlias($alias);
        }

        $push->iosNotification($content, $push_setting_array);
        $push->androidNotification($content, $push_setting_array);
        $push->setOptions(null, 86400, null, false); //false 测试环境  true 生产环境
        try {
            $return = $push->send();
            return json_encode($return);
        }catch (\JPush\Exceptions\APIConnectionException $e){

        }catch (\JPush\Exceptions\APIRequestException $e){

        }

        return true;
    }

    /**
     * 订单成交后将积分赠送给对应用户
     *
     * @param $orders_id
     * @return bool
     * @throws \Doctrine\DBAL\DBALException
     */
    public function give($orders_id)
    {
        $conn = $this->get('database_connection');
        $orders = $conn->fetchAssoc("SELECT id,user_id FROM orders WHERE id = ?", array($orders_id));
        $integral_details = $conn->fetchAssoc("SELECT id,user_id,integral FROM integral_details WHERE orders_id = ? AND subset_user_id = ?", array($orders_id, $orders['user_id']));
        $conn->executeUpdate("UPDATE user SET integral = ( integral + {$integral_details['integral']} ) WHERE id = {$integral_details['user_id']}");
        $conn->update('integral_details', array('is_obtain'=>1), array('id'=>$integral_details['id']));

        return true;
    }

//    public function refund($orders_id)
//    {
//        //TODO 订单线上退款相关操作
//
//        $conn = $this->get('database_connection');
//        $orders = $conn->fetchAssoc("SELECT id,user_id,total_price,trade_no FROM orders WHERE id = ?", array($orders_id));
//        if ($orders['status'])
//            return array('errorCode'=>1, 'message'=>'');
//    }

    /**
     * 调用其他bundle数据
     *
     * @param $BundleControllerAction
     * @param array $path
     * @return mixed
     */
    public function getApiData($BundleControllerAction, array $path = array())
    {
        $path = array_merge($path, $_POST, $_GET);
        $path['_route'] = $this->get('request')->get('_route');

        $bundle_info = $this->forward($BundleControllerAction, $path)->getContent();
        $data =  json_decode($bundle_info, TRUE);
        if(!is_array($data)){
            exit($bundle_info);
        }

        if($data['errorCode'] == -1){
            if ($_SERVER['REQUEST_METHOD'] == 'POST')
                return new JsonResponse($data);
            return $this->redirectToRoute('wx_login');
        }

        return $data;
    }
}
